﻿namespace FBlog.Core.Repositories

open System
open FBlog.Core

[<AutoOpen>]
module internal RavenDb =

    let useRavenSession(store : Raven.Client.IDocumentStore, saveChanges : bool) using  =
        use session = store.OpenSession()
        let result = using session
        if saveChanges then session.SaveChanges()
        result

type BlogPostRepository(ravenDbStore : Raven.Client.IDocumentStore) =

    let readFromSession = useRavenSession (ravenDbStore, false)
    let saveToSession = useRavenSession (ravenDbStore, true)

    let store(post : BlogPost) =
        saveToSession (fun session -> session.Store(post))

    let loadById(id : Guid) =
        let obj = readFromSession (fun session -> session.Load<BlogPost>(id))
        if Unchecked.defaultof<BlogPost> = obj then None else Some obj

    interface IBlogPostRepository with
        member i.Load(id) = loadById(id)
        member i.Save(post) = post |> store

    interface System.IDisposable with
        member i.Dispose() = ravenDbStore.Dispose()
        